package pl.planito.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class PasswordUtility {
	private StringBuilder salt;
	
	public PasswordUtility() {
			generateSalt();
	}
	
	private void generateSalt(){
		int r;
		
		Random random = new Random();
		
		for(int i=0; i<45; i++){
			r = random.nextInt(255)+1;
			salt.append((char)r);
		}
		
	}
	
	/**
	 * 
	 * @param password
	 * @return
	 */
	public String getMD5(StringBuilder password){
		byte[] utfPassword = null;
		MessageDigest messageDigest = null;
		byte[] md5Password = null;
		password.append(salt);
		
		try {
			utfPassword = password.toString().getBytes("UTF-8");
			messageDigest = MessageDigest.getInstance("MD5");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		
		if(messageDigest!=null)
			md5Password = messageDigest.digest(utfPassword);
		
		
		return md5Password.toString();
	}
	
	public String getSalt() {
		return salt.toString();
	}
	
	
	
}
